package org.rc.dao;

import com.google.appengine.api.datastore.Cursor;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.rc.model.Athlete;
import org.rc.model.Race;
import org.rc.model.Result;

/**
 *
 * @author dokeeffe
 */
public class ResultDao extends GenericDao<Result> {

    /**
     * Constructor
     * @param
     */
    public ResultDao() {
        super(Result.class);
    }

    /**
     * Gets all results. TODO. This may need changing for large races
     * @param race
     * @return 
     */
    public List<Result> getAllResultsForRace(Race race) {
        return listByProperty("race", race);
    }

    /**
     * Get a page of results for a race based on a start point
     * @param race
     * @param start
     * @param pagesize
     * @return
     */
    public List<Result> getResultsForRace(Race race, Integer start, Integer pagesize) {
        Query q = ofy().query(Result.class);
        q.filter("race",race);
        q.order("place");
        q.offset(start);
        q.limit(pagesize);
        return q.list();
    }

    /**
     * Get a page of results for a race based on a cursor
     * @param results - an empty list to be populated
     * @param race
     * @param cursor
     * @param pagesize
     * @return - a new cursor for the end point
     */
    public String getResultsForRace(List<Result> results, Race race, String cursor, Integer pagesize) {
        Query q = ofy().query(Result.class);
        q.filter("race",race);
        q.order("place");
        return getAllFromCursorForQuery(q,results,cursor,pagesize);
    }

    /**
     * Get results for an athlete
     * @param athlete
     * @return 
     */
    public List<Result> getResultsForAthlete(Athlete athlete) {
        List<Result> results = listByProperty("athlete", athlete);
        List<Key<Race>> raceKeys = new ArrayList<Key<Race>>();
        for(Result r : results) {
            raceKeys.add(r.getRace());
        }
        Map<Key<Race>, Race> races = ofy().get(raceKeys);
        for(Result r : results) {
            r.setRaceBean(races.get(r.getRace()));
        }

        return results;
    }
}
